import json

from django.http.response import JsonResponse

from utils import get_static_url
from .impl import gen_ca_cert, cert_info, gen_kubeconfig


def gen_ca_view(request):
    # 签发ca证书以及根据ca证书签发server证书

    params = json.loads(request.body.decode("utf-8"))
    data, err = gen_ca_cert(params)
    if err:
        return JsonResponse({"code": -1, "message": err, "data": {}})

    result = get_static_url(data)
    return JsonResponse({"code": 0, "message": "success", "data": result})


def cert_info_view(request):
    # 获取证书信息
    params = json.loads(request.body.decode("utf-8"))
    data, err = cert_info(params)
    if err:
        return JsonResponse({"code": -1, "message": err, "data": {}})
    return JsonResponse({"code": 0, "message": "success", "data": data})


def gen_kubeconfig_view(request):
    params = json.loads(request.body.decode("utf-8"))
    kubeconfig_path, err = gen_kubeconfig(params)
    if err:
        return JsonResponse({"code": -1, "message": err, "data": ""})

    return JsonResponse({"code": 0, "message": "success", "data": get_static_url(kubeconfig_path)})
